﻿using BaoShouTang.DBModel;
using BaoShouTangServer.ApiModels;
using BaoShouTangServer.Models;
using BaoShouTangServer.Service;
using Microsoft.Ajax.Utilities;
using MSXML2;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using UFIDA.U8.U8APIFramework;
using UFIDA.U8.U8MOMAPIFramework;

namespace BaoShouTangServer.ApiServies
{
    public class RdispService
    {
        public static string 生成退货单(U8Login.clsLogin u8Login, Sales_FHD_T sales_FHD_T, List<RDispatchLists> rDispatchLists, ref string dlid, ref string 材料出库单接口返回result)
        {
            //第二步：构造环境上下文对象，传入login，并按需设置其它上下文参数
            U8EnvContext envContext = new U8EnvContext();
            envContext.U8Login = u8Login;

            //设置上下文参数
            envContext.SetApiContext("VoucherType", "10"); //上下文数据类型：int，含义：单据类型：9



            //第三步：设置API地址标识(Url)
            //当前API：添加新单据的地址标识为：U8API/MaterialOut/Add
            U8ApiAddress myApiAddress = new U8ApiAddress("U8API/ReturnOrder/Save");


            //第四步：构造APIBroker
            U8ApiBroker broker = new U8ApiBroker(myApiAddress, envContext);

            //第五步：API参数赋值

            //给普通参数sVouchType赋值。此参数的数据类型为System.String，此参数按值传递，表示单据类型：11
            //broker.AssignNormalValue("sVouchType", "9");



            //给BO表头参数DomHead赋值，此BO参数的业务类型为材料出库单，属表头参数。BO参数均按引用传递
            //提示：给BO表头参数DomHead赋值有两种方法

            DataTable Dt_data = new DataTable();

            DbHelperSQL.connectionString = u8Login.UFDataConnstringForNet;
            StringBuilder strMsg = new StringBuilder();
            StringBuilder Strsql = new StringBuilder();

            //创建临时表
            string StrHeadName = "Sales_FHD_T" + Guid.NewGuid().ToString().Replace("-", "");
            string StrBodyName = "Sales_FHD_W" + Guid.NewGuid().ToString().Replace("-", "");
            Strsql.Append(" select  top 0  * into " + StrHeadName + " from Sales_FHD_T Where 1=1");
            Strsql.Append(" \n select  top 0  *  into " + StrBodyName + " from Sales_FHD_W Where 1=1");
            DbHelperSQL.ExecuteSql(Strsql.ToString());
            int id = (int)SnowFlakeSingle.Instance.NextId();
            int zpurRkdHead = 退货单头赋值(StrHeadName, id, sales_FHD_T);
            int zpurRkdTailList = 退货单体赋值(StrBodyName, id, rDispatchLists);
            //塞入临时表

            Strsql = new StringBuilder();
            Strsql.Append("select editprop='A',* from " + StrHeadName);
            DOMDocument domHead = Pub.getDom(Strsql.ToString(), u8Login.UfDbName);
            Strsql = new StringBuilder();
            Strsql.Append("select editprop='A',* from " + StrBodyName);
            DOMDocument domBody = Pub.getDom(Strsql.ToString(), u8Login.UfDbName);

            Strsql = new StringBuilder();
            Strsql.Append(" if not object_id('" + StrHeadName + "') is null drop table " + StrHeadName);
            Strsql.Append(" if not object_id('" + StrBodyName + "') is null drop table " + StrBodyName);

            DbHelperSQL.ExecuteSql(Strsql.ToString());

            broker.AssignNormalValue("DomHead", domHead);
            //方法一是直接传入MSXML2.DOMDocumentClass对象
            broker.AssignNormalValue("domBody", domBody);


            //给普通参数VoucherState赋值。此参数的数据类型为int，此参数按值传递，表示状态:0增加;1修改
            broker.AssignNormalValue("VoucherState", 0);


            //该参数VouchId为INOUT型普通参数。此参数的数据类型为System.String，此参数按值传递。在API调用返回时，可以通过GetResult("VouchId")获取其值
            string VouchId = "";
            broker.AssignNormalValue("vNewID", VouchId);

        
            //第六步：调用API
            if (!broker.Invoke())
            {
                //错误处理
                Exception apiEx = broker.GetException();
                if (apiEx != null)
                {
                    if (apiEx is MomSysException)
                    {
                        MomSysException sysEx = apiEx as MomSysException;
                        材料出库单接口返回result = ("系统异常：" + sysEx.Message);
                        //todo:异常处理
                    }
                    else if (apiEx is MomBizException)
                    {
                        MomBizException bizEx = apiEx as MomBizException;
                        材料出库单接口返回result = ("API异常：" + bizEx.Message);
                        //todo:异常处理
                    }
                    //异常原因
                    String exReason = broker.GetExceptionString();
                    if (exReason.Length != 0)
                    {
                        材料出库单接口返回result = ("异常原因：" + exReason);
                    }
                }
                //结束本次调用，释放API资源
                broker.Release();
            }

            //第七步：获取返回结果

            //获取返回值
            //获取普通返回值。此返回值数据类型为System.String，此参数按值传递，表示错误描述：空，正确；非空，错误
            //System.String result = broker.GetReturnValue() as System.String;
            //材料出库单接口返回result = result;
            //获取普通OUT参数curID。此返回值数据类型为string，在使用该参数之前，请判断是否为空
            //string curIDRet = broker.GetResult("curID") as string;
            //获取普通OUT参数CurDom。此返回值数据类型为MSXML2.IXMLDOMDocument2，在使用该参数之前，请判断是否为空
            //MSXML2.IXMLDOMDocument2 CurDomRet = Convert.ToObject(broker.GetResult("CurDom"));
            //到货单接口返回result += JsonConvert.SerializeObject(broker.GetResult("CurDom"));


            //获取返回值
            //获取普通返回值。此返回值数据类型为System.String，此参数按值传递，表示成功返回空串
           string  result = broker.GetReturnValue() as System.String;


            //获取普通INOUT参数VouchId。此返回值数据类型为System.String，在使用该参数之前，请判断是否为空
            System.String VouchIdRet = broker.GetResult("vNewID") as string;
            dlid = VouchIdRet;
            //获取普通OUT参数domMsg。此返回值数据类型为MSXML2.IXMLDOMDocument2，在使用该参数之前，请判断是否为空
            //MSXML2.IXMLDOMDocument2 domMsgRet = Convert.ToObject(broker.GetResult("domMsg"));

            //材料出库单接口返回result += JsonConvert.SerializeObject(broker.GetResult("domMsg"));
            //结束本次调用，释放API资源
            broker.Release();
            return result;

        }

        private static int 退货单头赋值(string strHeadName, int id, Sales_FHD_T sales_FHD_T)
        {
             sales_FHD_T.dlid = id;
            sales_FHD_T.iverifystate = null;
            sales_FHD_T.csysbarcode = null;
            sales_FHD_T.ivouchstate = "0";

            sales_FHD_T.ddate = DateTime.Now.ToString("yyyy-MM-dd");
            sales_FHD_T.cmodifier = null;
            sales_FHD_T.dmoddate = null;
            sales_FHD_T.cverifier = null;
            sales_FHD_T.dverifydate = null;
            sales_FHD_T.breturnflag = 1;
     
            return SqlSugarHelp.scope.Insertable(sales_FHD_T).AS(strHeadName).ExecuteCommand() ;
        }

        private static int 退货单体赋值(string strBodyName, int id, List<RDispatchLists> rDispatchLists)
        {
            List<Sales_FHD_W> sales_FHD_WList = new List<Sales_FHD_W>();
            foreach (var rDispatch in rDispatchLists)
            {
                Sales_FHD_W sales_FHD_W = SqlSugarHelp.scope.Queryable<Sales_FHD_W>().Where(it => it.autoid == rDispatch.AutoID).First();
                rdrecords32 rdrecords32 = SqlSugarHelp.scope.Queryable<rdrecords32>().Where(it => it.iDLsID == sales_FHD_W.idlsid).First();

                if (sales_FHD_W != null)
                {
                    sales_FHD_W.dlid = id;
                    sales_FHD_W.autoid = (int)SnowFlakeSingle.Instance.NextId();
                    sales_FHD_W.icorid = (int?)(rdrecords32?.iDLsID);
                    sales_FHD_W.ccorcode = rdrecords32?.cbdlcode;
                    sales_FHD_W.ccorcode = rdrecords32?.cbdlcode;
                    sales_FHD_W.isaleoutid = rdrecords32?.AutoID;

                    sales_FHD_W.iquantity = rDispatch.iQuantity.GetValueOrDefault() > 0 ? -rDispatch.iQuantity.GetValueOrDefault() : rDispatch.iQuantity.GetValueOrDefault();
                    sales_FHD_W.imoney = sales_FHD_W.iquantity * sales_FHD_W.iunitprice;
                    sales_FHD_W.itax = sales_FHD_W.imoney * sales_FHD_W.itaxrate /100;
                    sales_FHD_W.inatmoney = sales_FHD_W.iquantity * sales_FHD_W.inatunitprice;
                    sales_FHD_W.inattax = sales_FHD_W.inatmoney * sales_FHD_W.itaxrate / 100;
                    sales_FHD_W.inatsum = sales_FHD_W.inatmoney + sales_FHD_W.inattax;
                    sales_FHD_W.isum = sales_FHD_W.imoney + sales_FHD_W.itax;
                    sales_FHD_W.cdefine23 = rDispatch.docid;
                    sales_FHD_W.cdefine24 = rDispatch.guid.ToString();
                    //sales_FHD_W.foutquantity = sales_FHD_W.iquantity;
                    //sales_FHD_W.funsignquantity = sales_FHD_W.iquantity;
                    sales_FHD_WList.Add(sales_FHD_W);
                }
            }
            return SqlSugarHelp.scope.Insertable(sales_FHD_WList).AS(strBodyName).ExecuteCommand();
        }

    }
}